 /* *********
  *    Author: chenjianbin;
  *    Copyright: formData upload;
  *    Date: 2016-08-25;
  *    File: app-manage.js;
  ********* */
import { hashHistory } from 'react-router';
import Tool from './ToolUtils.js';

/**
 * 发送ajax请求和服务器交互
 * @param {object} mySetting 配置ajax的配置
 */
const FileUploadTool = {};
FileUploadTool.ajax = function (mySetting) {
    // console.log('=============')
    // console.log(mySetting)
  let setting = {
    url: window.location.pathname, // 默认ajax请求地址
    async: true, // true。默认设置下，所有请求均为异步请求。如果需要发送同步请求，请将此选项设置为 false
    options: {}, // 发给服务器的数据
    uploadProgress: function (e) {}, // 上传进度方法
    success: function (text) {}, // 请求成功执行方法
    error: function () { }, // 请求失败执行方法
    token: Tool.locals.getSession('token')
  };

  // 属性覆盖
  for (const attr in mySetting) {
    setting[attr] = mySetting[attr];
  }
  if (typeof XMLHttpRequest === 'undefined') {
    return;
  }
  const xhr = new XMLHttpRequest();
  const formData = new FormData();
  formData.append(setting.options.filename,setting.options.file);
  if (setting.options.data) {
    for (const i in setting.options.data) {
      formData[i] = setting.options.data[i];
    }
  }
  xhr.open('post', setting.url, setting.async);
  function uploadProgress(e) {
    const progressData = {};
    progressData.loaded = (e.loaded / 1024 / 1024).toFixed(1);
    progressData.total = (e.total / 1024 / 1024).toFixed(1);
    progressData.Pregress = Math.min(100, parseInt(100.0 * e.loaded / e.total));
    setting.uploadProgress(progressData);
  }
  xhr.upload.onprogress = uploadProgress; // 监听返回进度

  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('token', setting.token);
  xhr.send(formData);
  // 取消上传
  // ==============
  FileUploadTool.abort = function () {
    xhr.abort(xhr);
  };
  // 监听readyState
  // ===============
  if (setting.async) {
    xhr.addEventListener('readystatechange', httpEnd, false);
  } else {
    httpEnd();
  }
  // 请求完成执行
  // =============
  function httpEnd() {
    if (xhr.readyState === 4) {
      const head = xhr.getAllResponseHeaders();
      let response = xhr.responseText;
      // 将服务器返回的数据，转换成json

      if (/application\/json/.test(head) || setting.dataType === 'json' && /^(\{|\[)([\s\S])*?(\]|\})$/.test(response)) {
        response = JSON.parse(response);
      }
      if (xhr.status === 200 || xhr.status === 201) {
        response.code === 401 || response.code === 10002 ? hashHistory.push('/login') : setting.success(response, setting, xhr);
          // 监听返回成功函数
      } else {
        setting.error(xhr, setting); //监听返回失败函数
      }
    }
  }
  xhr.end = function () {
    xhr.removeEventListener('readystatechange', httpEnd, false);
  };
};

FileUploadTool.post = function (pathname, data, success, uploadProgress, error) {
  const setting = {
    url: pathname, // 默认ajax请求地址
    options: data, // 发给服务器的数据
    success: success || function () { }, // 请求成功执行方法
    uploadProgress: uploadProgress || function () { }, // 执行进度方法
    error: error || function () { } // 请求失败执行方法
  };
  return FileUploadTool.ajax(setting);
};

export default FileUploadTool;

/*********
eg:
 <input type='file' id='upload_file' name='file' onChange={this.fileChange}/>
function fileChange(e) {
  let data = {filename: 'file',file: e.target.files[0]}
  uploadFile(data)
}
uploadFile = (data) =>{
  FileUploadTool.post(
    api,data,
    (res) => {console.log(res)}, //请求成功执行方法
    (ProgressData) =>{  //执行进度方法
      console.log(ProgressData)
    },
    (error) => {} //请求失败执行方法
  )
}

**********/

